﻿using DotNetCore.CAP; 
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Req;
using SkyApm.Tracing;
using SkyApm.Tracing.Segments;
using System;
using System.Collections.Generic;

namespace SHKF.B2C.Service.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class ProductController : Base2Controller
    {
        private string Prefix = "SHKF.B2C";

        private readonly ProductInfoBLL productInfoBLL;
        private readonly ProductBaseBLL productBaseBLL;
        private readonly ShopBLL shopBLL;
        private readonly ShopMapBLL shopMapBLL;

        public ProductController(
            ProductInfoBLL productInfoBLL,
            ProductBaseBLL productBaseBLL,
            ShopBLL shopBLL,
            ShopMapBLL shopMapBLL,
            IServiceProvider serviceProvider,
            ILogger<ProductController> logger) : base(serviceProvider, logger)
        {
            this.productInfoBLL = productInfoBLL;
            this.productBaseBLL = productBaseBLL;
            this.shopBLL = shopBLL;
            this.shopMapBLL = shopMapBLL;
        }

        #region 上传产品

        /// <summary>
        /// 上传产品信息
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        [HttpPost("Save")]
        public DataDto Save(ProductInfo product)
        {
            DataDto dto = new DataDto();
            try
            {
                string strMsg = "";
                if (string.IsNullOrEmpty(product.ID))
                {
                    strMsg = "编号不能为空!";
                }

                if (string.IsNullOrEmpty(product.Upc))
                {
                    strMsg = "Upc不能为空!";
                }

                if (product.ShopSN <= 0)
                {
                    strMsg = "ShopSN不能为空!";
                }

                if (product.CompanySN == 0)
                {
                    List<ShopEntity> list = this.shopBLL.Query(product.ShopSN);

                    if (list == null && list.Count == 0)
                    {
                        strMsg = $"ShopSN:{product.ShopSN}没有创建虚拟店铺";
                    }
                    else
                    {
                        product.CompanySN = list[0].CompanySN;
                    }
                }

                if (strMsg != "")
                {
                    dto.error = new Error() { code = -1, msg = strMsg };
                }
                else
                {
                    base.AddLog($"1.0 => start");
                    base.AddLog(JsonConvert.SerializeObject(product));

                    //1.保存商品库
                    SaveProductBase(product);
                    base.AddLog($"1.1 => 保存商品库 Upc:{product.Upc}");

                    //2.批量保存到店铺商品表 
                    SaveShopProduct(product);
                    base.AddLog($"1.2 => 批量保存到商品表");

                    //3.发到Cap
                    dto.TraceId = PublishCap(product);
                }
            }
            catch (Exception e)
            {
                dto.SetException(e);
            }

            return dto;
        }

        private void SaveProductBase(ProductBaseEntity product)
        {
            ProductBaseEntity data = this.productBaseBLL.Get(product.Upc);
            if (data == null) //如果商品库中不存在则添加，后期在管理界面维护详细信息
            {
                data = this.productBaseBLL.Save(product);
            }

            product.SN = data.SN; //为了保存门店商品 
        }

        private ProductInfoEntity SaveShopProduct(ProductInfo product)
        {
            product.FKSN = product.SN;  //商品库SN

            ProductInfoEntity productInfoEntity = new ProductInfoEntity();
            productInfoEntity.FKSN = product.SN;
            productInfoEntity.ShopSN = product.ShopSN;
            productInfoEntity.CompanySN = product.CompanySN;
            productInfoEntity.ID = product.ID;
             
            //保存到商品库
            ProductInfoEntity data = this.productInfoBLL.Save(productInfoEntity); 
            product.SN = data.SN;       //为了保存门店商品 
            return data;
        }

        private string PublishCap(ProductInfo product)
        {
            string strTraceId = base.CreateTraceId();

            int index = 1;
            foreach (string platName in PlatformList)
            {
                //检查店铺是否映射平台 
                long ShopSN = product.ShopSN;
                bool isExist = this.shopMapBLL.IsExist(ShopSN, platName);

                if (isExist)
                {
                    //保存映射表  
                    ProductInfoMapEntity productMap = new ProductInfoMapEntity();
                    productMap.FKSN = product.SN;  //门店商品SN,此时FKSN为门店商品SN
                    productMap.pDate = DateTime.Now;
                    productMap.Platform = platName;
                    productMap.app_medicine_code = product.ID;
                    productMap.Upc = product.Upc;

                    productInfoBLL.MapSave(productMap);

                    string name = $"{Prefix}.{platName}.Product.Save";

                    //发送之前判断分店是否已经配置第三方平台店铺SN
                    Console.WriteLine(name);
                    base.Publish(name, product, strTraceId);
                    base.AddLog($"1.3.{index} => 向{name}发送消息");
                }
                else
                {
                    base.AddLog($"1.3.{index} => 所有店铺都没有配置{platName}的信息");
                }
                index++;
            }

            return strTraceId;
        }

        #endregion

        #region 更新库存

        [HttpPost("Stock")]
        public DataDto Stock(StockInfo data)
        {
            DataDto dto = new DataDto();
            try
            {
                if (data.Items.Count > 200)
                {
                    dto.error = new Error() { code = -1, msg = "可传药品库存数据限定不超过200组" };
                    return dto;
                }

                string strTraceId = base.CreateTraceId();

                int index = 1;
                foreach (string platName in PlatformList)
                {
                    //检查店铺是否映射平台 
                    long ShopSN = data.ShopSN;
                    bool isExist = this.shopMapBLL.IsExist(ShopSN, platName); 
                    if (isExist)
                    {
                        //保存映射表   
                        string name = $"{Prefix}.{platName}.Product.Stock";

                        //发送之前判断分店是否已经配置第三方平台店铺SN
                        Console.WriteLine(name);
                        base.Publish(name, data, strTraceId);
                        base.AddLog($"1.0.{index} => 向{name}发送消息");
                    }
                    else
                    {
                        base.AddLog($"1.0.{index} => 所有店铺都没有配置{platName}的信息");
                    }
                    index++;
                }

                dto.TraceId = strTraceId;
            }
            catch (Exception e)
            {
                dto.SetException(e);


            }
            return dto;
        }

        #endregion

        #region 更新价格

        [HttpPost("Price")]
        public DataDto Price(StockInfo data)
        {
            DataDto dto = new DataDto();
            try
            {
                if (data.Items.Count > 200)
                {
                    dto.error = new Error() { code = -1, msg = "可传药品库存数据限定不超过200组" };
                    return dto;
                }

                string strTraceId = base.CreateTraceId();

                int index = 1;
                foreach (string platName in PlatformList)
                {
                    //检查店铺是否映射平台 
                    long ShopSN = data.ShopSN;
                    bool isExist = this.shopMapBLL.IsExist(ShopSN, platName);
                    if (isExist)
                    {
                        //保存映射表   
                        string name = $"{Prefix}.{platName}.Product.Price";

                        //发送之前判断分店是否已经配置第三方平台店铺SN
                        Console.WriteLine(name);
                        base.Publish(name, data, strTraceId);
                        base.AddLog($"1.0.{index} => 向{name}发送消息");
                    }
                    else
                    {
                        base.AddLog($"1.0.{index} => 所有店铺都没有配置{platName}的信息");
                    }
                    index++;
                }

                dto.TraceId = strTraceId;
            }
            catch (Exception e)
            {
                dto.SetException(e);


            }
            return dto;
        }

        #endregion

    }
}
 
